package com.mach.platform.controller;

import com.mach.platform.domain.Response;
import com.mach.platform.domain.iot.IotDevType;
import com.mach.platform.innotation.DelCache;
import com.mach.platform.service.IotDevServiceImpl;
import com.mach.platform.service.IotDevTypeServiceImpl;
import com.mach.platform.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author Administrator
 * @Description: 设备库控制器
 * @Package: com.mach.platform.controller
 * @time 2018/4/26 0026 15:21
 */
@Api(tags = { "设备类型接口" })
@RestController
@RequestMapping("/iot/devType")
public class IotDevTypeCtrl extends BaseCtrl<IotDevType> {

	@Autowired
	private IotDevTypeServiceImpl iotDevTypeService;

	@Autowired
	private IotDevServiceImpl iotDevService;

	/**
	 * -- @GetMapping(value = "/info/{id}")
	 * -- @ApiOperation(value = "单个实体信息", notes = "接口备注：无", produces = "application/json")
	 * 单个数据 的接口
	 * -- @PathVariable(value = "id", required = true) Long id
	 *
	 * @param id 数据的id
	 * @return Response
	 */
	@ApiOperation(value = "查询单个实体", notes = "单实例数据查询", produces = "application/json")
	@GetMapping(value = "/info")
	@Override
	public Response info (Long id) {
		return Response.ok(iotDevTypeService.info(id));
	}

	/**
	 * --	@ApiOperation(value = "列表--分页", produces = "application/json", notes = "列表参数：size(每页数量),page(页码),searchParam(查询内容)")
	 * -- @GetMapping(value = "/xxxs")
	 * 获取列表数据
	 * -- @PageableDefault(size = 25) Pageable pageable
	 * -- @RequestParam Map params
	 *
	 * @param pageable 分页参数
	 * @param params   其他参数
	 * @return Response
	 */
	@ApiOperation(value = "列表--分页", produces = "application/json", notes = "列表参数：size(每页数量),page(页码),searchParam(查询内容)")
	@GetMapping(value = "/list")
	@Override
	public Response list (@PageableDefault(size = 50,sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam Map params) {

		Page<IotDevType> dbResult = iotDevTypeService.list(pageable, params);

		return Response.ok(dbResult);
	}

	/**
	 * -- @DeleteMapping("/del")
	 * -- @ApiOperation(value = "删除", notes = "接口备注：无", produces = "application/json")
	 * 删除数据
	 * -- @RequestBody Long[] ids
	 *
	 * @param ids id的集合
	 * @return Response
	 */
	@ApiOperation(value = "删除", notes = "接口备注：无", produces = "application/json")
	@DeleteMapping("/del")
	@Override
	public Response delete (@RequestBody Long[] ids) {
		boolean falg = iotDevService.checkDeviceHasDependency(ids);
		if (falg) {
			return Response.error("当前设备类型已有相关依赖设备，不允许删除");
		}
		Integer nums = iotDevTypeService.delete(ids);
		return Response.ok(nums);
	}

	/**
	 * --@PostMapping("/save")
	 * --	@ApiOperation(value = "保存", notes = "接口备注：无", produces = "application/json")
	 * 保存一个 对象
	 * --@RequestBody T t
	 *
	 * @param type 保存的实体
	 * @return Response
	 */
	@ApiOperation(value = "保存", notes = "接口备注：无", produces = "application/json")
	@PostMapping("/save")
	@Override
	public Response save (@RequestBody IotDevType type) {

		return Response.ok(iotDevTypeService.save(type));
	}

	/**
	 * --@PutMapping("/upd")
	 * --	@ApiOperation(value = "更新", notes = "接口备注：无", produces = "application/json")
	 * 更新一个对象
	 * --@RequestBody T t
	 *
	 * @param type 更新的实体
	 * @return Response
	 */
	@ApiOperation(value = "更新", notes = "接口备注：无", produces = "application/json")
	@PutMapping("/upd")
	@Override
	public Response update (@RequestBody IotDevType type) {

		return Response.ok(iotDevTypeService.update(type));
	}

	/**
	 * 获取 设备类型 的图标配置 上传图片数据
	 * @return
	 */
	@GetMapping("icons")
	public Response getIconDeviceOptions ( ) {

		Map iconDeviceOptions = iotDevTypeService.getIconDeviceOptions();

		return Response.ok(iconDeviceOptions);
	}

	/**
	 * icon 图片制空
	 * @return
	 */
	@GetMapping("/empty/{id}")
	public Response seticonempty (@PathVariable("id") Long id) {
			iotDevTypeService.uploadPic(id, null);
			return Response.ok("清空地址完成！");
	}



	/**
	 * 上传设备类型图片
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "上传设备类型图片", notes = "接口备注：无", produces = "application/json")
	@PostMapping("/upload/{id}")
	public Response uploadPic (@ApiParam(name = "id", value = "设备id", required = true) @PathVariable("id") Long id,
			@ApiParam(name = "pic", value = "固定名称pic", required = false) @RequestParam("pic") MultipartFile file) {

		if (file == null) {
			return Response.error("上传图片为空，上传失败，请检查！");
		}

		//  if upload ? delete old file : ignore                      ------start
		boolean picExits = false;
		String oldUrl = "";
		IotDevType oldone = iotDevTypeService.info(id);
		if (oldone.getIconUrl() != null) {
			picExits = true;
			oldUrl = oldone.getIconUrl();
		}
		//  if upload ? delete old file : ignore                      ------end

		File finalSave = null;

		try {

			String rootPath = getPicSavePath();

			File targetPath = new File(getPicSavePath(), "/pic");
			if (!targetPath.exists()) {
				targetPath.mkdirs();
			}

			String originalName = file.getOriginalFilename();
			String sufferName = originalName.substring(originalName.lastIndexOf("."));
			String picName = UUIDUtils.generateUUID() + sufferName;

			finalSave = new File(targetPath.getPath() + File.separator + picName);

			// 保存图片zhixing
			FileUtils.copyInputStreamToFile(file.getInputStream(), finalSave);

			// 保存地址 dao数据库
			iotDevTypeService.uploadPic(id, finalSave.getAbsolutePath());

			// 删除 旧的文件
			if (picExits) {
				FileUtils.forceDelete(new File(oldUrl));
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return Response.ok(finalSave.getAbsoluteFile());
	}

	/**
	 * 获取 jar包所在 目录路径
	 *
	 * @return
	 */
	public String getPicSavePath ( ) {
		ApplicationHome home = new ApplicationHome(getClass());
		File jarFile = home.getSource();
		return jarFile.getParentFile().getParentFile().getAbsolutePath();
	}

}
